﻿using Framework.ExtensionsMods.RemoteRequest;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Framework.ExtensionsMods.Extension
{
	public static class RemoteRequestExtension
	{
		/// <summary>
		/// 注册远程请求
		/// </summary>
		/// <param name="services"></param>
		/// <param name="ApproveAllCerts">是否忽略 SSL 不安全检查，或 https 不安全或 https 证书有误,默认为 false</param>
		/// <param name="HandlerLifetime">客户端生存期,默认为 5 分钟</param>
		/// <returns></returns>
		public static IServiceCollection AddRemoteRequest(this IServiceCollection services,bool ApproveAllCerts = false,long HandlerLifetime = 5)
		{
			services.AddTransient<HttpHelper>();        // 注册Http连接操作帮助类

			IHttpClientBuilder httpClientBuilder = services.AddHttpClient(string.Empty)
				.SetHandlerLifetime(TimeSpan.FromMinutes(HandlerLifetime)); // 设置客户端生存期,默认为 5 分钟

			if (ApproveAllCerts)    
			{
				// 忽略 SSL 不安全检查，或 https 不安全或 https 证书有误
				httpClientBuilder.ConfigurePrimaryHttpMessageHandler(u => new HttpClientHandler
				{
					ServerCertificateCustomValidationCallback = (_, _, _, _) => true,
				});

			}
			else
			{
				// 使用默认 SSL 证书
				httpClientBuilder.ConfigurePrimaryHttpMessageHandler(u => new HttpClientHandler
				   {
					   AllowAutoRedirect = true,
					   UseDefaultCredentials = true
				   });
			}

			return services;
		}
	}
}
